<?php

namespace App\Models\Back;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class Code extends Model
{
    /*
     * 生成代码
     * @param   array   $filed    字段信息
     * return   mix     成功返回true，失败返回错误信息数组
     */
    public function createCode ($filed)
    {
		$table = session('crud.table');
		//控制器和模型名,视图名,路由名
	    $nameList = $this->handleTable($table);

	    //获取字段集合
	    $fields = $filed;
	    //获取表的展示标题
	    $tableTitle = session('crud.title');

	    //定义错误
	    $error = array();

	    /***生成控制器代码文件***/
		$controller = $this->createController($nameList);
		if (!$controller) {
			$error[] = '控制器文件生成失败';
		}

		/***生成模型代码文件***/
		$model = $this->createModel($nameList);
	    if (!$model) {
		    $error[] = '模型文件生成失败';
	    }

	    /***生成视图代码文件***/
	    $viewList = $this->createViewList($tableTitle, $nameList, $fields);
	    if (!$viewList) {
		    $error[] = '列表视图文件生成失败';
	    }

	    if ($error) {
			return true;
	    } else {
			return $error;
	    }
    }

    /*
     * 生成控制器
     * @param   array      $nameList       名称数组
     * return   bool
     */
    private function createController ($nameList)
    {
	    //要搜索的字符列表
	    $search = ['__CONTROLLER__','__MODEL__','__VIEW__','__WEB__'];
	    //要替换的字符列表
	    $replace = [$nameList['name'],$nameList['name'],$nameList['view'],$nameList['web']];
	    //要替换的文件
	    $path = resource_path('views/template/templateController.php');
	    $file = file_get_contents($path);
	    //替换子字符串
	    $controllerFile = str_replace($search, $replace, $file);
	    //生成控制器的路径
	    $path = app_path('Http/Controllers/Back/'.$nameList['name'].'Controller.php');
	    //生成目录
	    if (!$this->createDir($path)) {
	    	return false;
	    }
	    //生成文件
	    if (file_put_contents($path, $controllerFile)) {
	    	return true;
	    } else {
	    	return false;
	    }
    }

    /*
     * 生成模型
     * @param   array      $nameList    名字列表
     * return   bool
     */
	private function createModel ($nameList)
    {
	    //要搜索的字符列表
	    $search = ['__MODEL__','__VIEW__', '__TABLE__'];
	    //要替换的字符列表
	    $replace = [$nameList['name'],$nameList['view'],$nameList['table']];
	    //要替换的文件
	    $path = resource_path('views/template/template.php');
	    $file = file_get_contents($path);
	    //替换子字符串
	    $modelFile = str_replace($search, $replace, $file);
	    //生成模型的路径
	    $path = app_path('Models/Back/'.$nameList['name'].'.php');
	    //生成目录
	    if (!$this->createDir($path)) {
		    return false;
	    }
	    //生成文件
	    if (file_put_contents($path, $modelFile)) {
		    return true;
	    } else {
		    return false;
	    }
    }

    /*
     * 生成视图list
     * @param   string      $title      表的展示标题
     * @param   array      $nameList    名称数组
     * @param   array       $fields     字段信息
     * return   bool
     */
    private function createViewList ($title, $nameList, $fields)
    {
    	/***处理列表表字段信息***/
    	$TheadPath = resource_path('views/template/templateListThead.blade.php');
    	$TheadPathSort = resource_path('views/template/templateListTheadSort.blade.php');
	    $TbodyPath = resource_path('views/template/templateListTbody.blade.php');
	    $setFieldPath = resource_path('views/template/templateSetField.blade.php');
	    $TheadFile = file_get_contents($TheadPath);
	    $TheadSortFile = file_get_contents($TheadPathSort);
	    $TbodyFile = file_get_contents($TbodyPath);
	    $setFieldFile = file_get_contents($setFieldPath);
	    $Thead = '';
	    $Tbody = '';
	    $setField = '';
    	foreach ($fields as $key => $field) {
			if (isset($field['is_list'])) {
				//表head
				if (isset($field['is_sort'])) {
					$Thead .= str_replace(
						['__VIEW__', '__FIELD__', '__TITLE__', '__WEB__'],
						[$nameList['view'], $key, $field['title'], $nameList['web']],
						$TheadSortFile
					);
				} else {
					$Thead .= str_replace('__TITLE__', $field['title'], $TheadFile);
				}
				//表body
				$Tbody .= str_replace('__FIELD__', $key, $TbodyFile);
			}
			//处理set
		    if (isset($field['is_set'])) {
			    $setField .= str_replace(
				    ['__VIEW__', '__FIELD__', '__TITLE__', '__WEB__'],
				    [$nameList['view'], $key, $field['title'], $nameList['web']],
				    $setFieldFile
			    );
		    }
	    }

		/***list***/
	    //要搜索的字符列表
	    $listSearch = ['__TITLE__','__VIEW__', '__THEAD__', '__TBODY__', '__WEB__'];
	    //要替换的字符列表
	    $listReplace = [$title,$nameList['view'], $Thead, $Tbody, $nameList['web']];
	    //要替换的文件
	    $listPath = resource_path('views/template/templateList.blade.php');
	    $listFile = file_get_contents($listPath);
	    //替换子字符串
	    $listViewFile = str_replace($listSearch, $listReplace, $listFile);
	    //生成模型的路径
	    $listPath = resource_path('views/back/'. $nameList['view'] .'/list.blade.php');


	    /***set***/
	    //要搜索的字符列表
	    $setSearch = ['__TITLE__','__VIEW__', '__FIELD__', '__WEB__'];
	    //要替换的字符列表
	    $setReplace = [$title,$nameList['view'], $setField, $nameList['web']];
	    //要替换的文件
	    $setPath = resource_path('views/template/templateSet.blade.php');
	    $setFile = file_get_contents($setPath);
	    //替换子字符串
	    $setViewFile = str_replace($setSearch, $setReplace, $setFile);
	    //生成模型的路径
	    $setPath = resource_path('views/back/'. $nameList['view'] .'/set.blade.php');

	    //生成目录
	    if (!$this->createDir($setPath)) {
		    return false;
	    }

	    //生成文件
	    if (file_put_contents($listPath, $listViewFile) && file_put_contents($setPath, $setViewFile)) {
		    return true;
	    } else {
		    return false;
	    }
    }

    /*
     * 检测文件路径中目录是否存在？不存在则生成
     */
    private function createDir($path)
    {
		$dir = dirname($path);
		if (!is_dir($dir)) {
			if (mkdir($dir)) {
				return true;
			} else {
				return false;
			}
		} else {
			return true;
		}
    }

    /*
     * 处理表名
     */
    private function handleTable($table)
    {
    	$nameList = array();
    	//转换成首字母大写并去掉_,转换成单数
	    $name = str_singular(studly_case($table));
	    //转换成驼峰式
		$viewName = camel_case(str_singular($table));
		//转换成-连接
	    $webName = str_slug(str_singular($table), '-');
	    $nameList['name'] = $name;
	    $nameList['view'] = $viewName;
	    $nameList['web'] = $webName;
	    $nameList['table'] = $table;
	    return $nameList;
    }
}
